import * as step from '@flow-step/step-toolkit'
import process from 'process'
import fs from 'fs'
import * as sinon from 'sinon'
import {expect} from 'chai'
import {afterEach, beforeEach} from 'mocha'
import * as install from '../src/install'


describe('install ossutil', () => {
    let sandbox = sinon.createSandbox()
    let addPath: sinon.SinonStub
    let stepInstallStub: sinon.SinonStub

    let chmodSyncStub: sinon.SinonStub
    let linkSyncStub: sinon.SinonStub
    let existsSyncStub: sinon.SinonStub
    beforeEach(() => {
        sandbox.stub(process, 'env').value({
            ...process.env,
            FLOW_TOOL_REGISTRY_URL: 'https://tool-registry-url.com',
            FLOW_RUNNER_TOOL_CACHE_DIR: '/tmp/flow_tools'
        })

        addPath = sandbox.stub(step, 'addPath')
        stepInstallStub = sandbox.stub(step.tool, 'install')

        chmodSyncStub = sandbox.stub(fs, 'chmodSync')
        linkSyncStub = sandbox.stub(fs, 'linkSync')
        existsSyncStub = sandbox.stub(fs, 'existsSync')
    })

    afterEach(() => {
        sandbox.restore()
        process.env.FLOW_RUNNER_TOOL_CACHE_DIR = ''
    })

    it('install ossutil', async () => {
        const installPath = '/path/to/install'
        stepInstallStub.resolves(installPath)
        existsSyncStub.returns(false)

        const ossutilVersion = 'v1.7.19'
        const result = await install.installOssutil(ossutilVersion)
        expect(stepInstallStub.callCount).to.equal(1)
        sinon.assert.calledWith(stepInstallStub, 'ossutil', ossutilVersion)
        sinon.assert.calledWith(chmodSyncStub, `${installPath}/ossutil`, 0o755)
        sinon.assert.calledWith(linkSyncStub, `${installPath}/ossutil-${ossutilVersion}`, `${installPath}/ossutil`)
        sinon.assert.calledWith(addPath, installPath)
    })

    it('skip install ossutil if cached', async () => {
        const installPath = '/path/to/install'
        stepInstallStub.resolves(installPath)
        existsSyncStub.returns(true)

        const ossutilVersion = 'v1.7.19'
        const result = await install.installOssutil(ossutilVersion)
        expect(stepInstallStub.callCount).to.equal(1)
        sinon.assert.calledWith(stepInstallStub, 'ossutil', ossutilVersion)
        sinon.assert.calledWith(chmodSyncStub, `${installPath}/ossutil`, 0o755)
        sinon.assert.calledWith(addPath, installPath)
    })


})
